package com.jiufengxinxi.ts.device.equipment;


import com.jiufengxinxi.ts.common.utils.HexUtil;
import com.jiufengxinxi.ts.common.utils.socket.ISocketRequestHandle;
import com.jiufengxinxi.ts.common.utils.socket.client.MultiThreadClient;
import com.jiufengxinxi.ts.common.utils.thread.ExecutorServiceUtils;
import com.jiufengxinxi.ts.common.utils.thread.LoopThreadRunnable;
import com.jiufengxinxi.ts.device.callback.IDeviceStateCallback;
import com.jiufengxinxi.ts.device.interfaces.IDviceGeneral;
import org.apache.commons.lang3.StringUtils;

public class IO88Device extends IDviceGeneral {
	
	private MultiThreadClient client;
	
	private boolean reading=false;
	
	private String password;
	
	private Thread sendThread;

	private IO88HexFilter io88HexFilter= null;
	
	public IO88Device(String ip,int port,String password) {
        io88HexFilter= new IO88HexFilter();
		client = new MultiThreadClient(ip,port);
		client.setCharFilter(io88HexFilter);
		this.password = password;
	}
	
	public void setHandler(ISocketRequestHandle socketRequestHandle) {
		client.setSocketRequestHandle(socketRequestHandle);
	}
	
	
	public void readInIOSinalSend() {
		//if(!reading) {
			
//			sendThread = new Thread(new Runnable() {
//				
//				@Override
//				public void start() {
//					while(true) {
//						try {
//							//System.out.println("send : "+IO88Sinal.SEND_READ_ALL_IN_IO);
//							client.send(HexUtil.toBytes(IO88Sinal.SEND_READ_ALL_IN_IO));
//							
//							Thread.sleep(80);
//						}catch (Exception e) {
//							e.printStackTrace();
//						}
//					}
//					
//				}
//			});
//			sendThread.start();
			ExecutorServiceUtils.execute(new LoopThreadRunnable() {
				
				@Override
				public boolean isUseLock() {
					return false;
				}
				
				@Override
				public String getName() {
					return "reading";
				}
				
				@Override
				public int sleepTime() {
					return 50;
				}
				
				@Override
				public void loopElement() {
					if(reading) {
						try {
							if(!client.isConnected()){
								startup();
							}else{
								client.send(HexUtil.toBytes(IO88Sinal.SEND_READ_ALL_IN_IO));
							}
						}catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				
				@Override
				public boolean endCondition() {
					return true;
				}
			});
		//}
		
	}
	
	/**
	 * 断开一路IO
	 * @param index
	 */
	public void breakOne(int index) {
		String sinal = IO88Sinal.SEND_BREAK_ONE_IO.replace("__", coverage(index));
		if(!client.isConnected()){
			startup();
		}
		client.send(HexUtil.toBytes(sinal));
	}
	
	/**
	 * 闭合一路IO
	 * @param index
	 */
	public void closeOne(int index) {
		String sinal = IO88Sinal.SEND_CLOSE_ONE_IO.replace("__", coverage(index));
		if(!client.isConnected()){
			startup();
		}
		client.send(HexUtil.toBytes(sinal));
	}
	
	
	/**
	 * 改变信号
	 * @param index
	 * @param sinal
	 */
	public void changeOne(int index,String sinal) {
		if(sinal.equals("00")) {
			breakOne(index);
		}else if(sinal.equals("01")){
			closeOne(index);
		}
	}
	
	
	private String coverage(int index) {
		String s = HexUtil.decimalToHex(index);
		if(s.length()==1) {
			s = "0"+s;
		}
		return s;
	}

	@Override
	public String status() {
		return check()?"connected":"disconnect";
	}

	@Override
	public boolean check() {
		return client.isConnected();
	}

	@Override
	public void destroy() {
		try {
			if(sendThread!=null) {
				sendThread.interrupt();
			}
			reading = false;
			client.disconnect();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void startup() {
		client.connection();
		client.send(HexUtil.toBytes(password));
		reading = true;
	}

	@Override
	public String getDeviceName() {
		return "IO88";
	}

	@Override
	public void initDevide(String... param) {
		startup();
	}

	public class IO88Sinal{
		//断开一路IO
		public static final String SEND_BREAK_ONE_IO =      "55aa00030001__05";
		public static final String RECIVE_BREAK_ONE_IO =    "81__";
		
		//闭合一路IO
		public static final String SEND_CLOSE_ONE_IO =      "55aa00030002__06";
		public static final String RECIVE_CLOSE_ONE_IO =    "82__";
		
		
		//取反一路
		public static final String SEND_NEGATION_ONE_IO =   "55aa00030003__07";
		public static final String RECIVE_NEGATION_ONE_IO = "83__";
		
		//全部断开
		public static final String SEND_BREAK_ALL_IO =      "55aa0003000406";
		public static final String RECIVE_BREAK_ALL_IO =    "84";
		
		//全部闭合
		public static final String SEND_CLOSE_ALL_IO =      "55aa0003000507";
		public static final String RECIVE_CLOSE_ALL_IO =    "85";
		
		//全部取反
		public static final String SEND_NEGATION_ALL_IO =   "55aa0003000608";
		public static final String RECIVE_NEGATION_ALL_IO = "86";
		
		//获取全部输出状态
		public static final String SEND_READ_ALL_OUT_IO =   "55aa0002000a0c";
		public static final String RECIVE_READ_ALL_OUT_IO = "8a____";
		
		//获取全部输入状态
		public static final String SEND_READ_ALL_IN_IO =    "55aa0002001416";
		public static final String RECIVE_READ_ALL_IN_IO =  "94____";
		
	}
	
	
	/**
	 * IO88专用编码指令过滤
	 * @author heshuangfeng
	 *
	 */
	public class IO88HexFilter extends MultiThreadClient.HexFilter{
		
		private int bitsit = 8;
		
		@Override
		public String change(byte[] bs) {
			String hex = "";
			//System.out.println(hex);
			
			try {
				hex = HexUtil.bytesToHexFun3(bs).substring(10);
				if(hex.startsWith(IO88Sinal.RECIVE_READ_ALL_IN_IO.replace("____", ""))) {
					hex = hex.length()> IO88Sinal.RECIVE_READ_ALL_IN_IO.length()?hex.substring(0, IO88Sinal.RECIVE_READ_ALL_IN_IO.length()):hex;
					hex = hex.replace(IO88Sinal.RECIVE_READ_ALL_IN_IO.replace("____", ""), "");
				}else if(hex.startsWith(IO88Sinal.RECIVE_READ_ALL_OUT_IO.split("____")[0])){
					hex = hex.length()> IO88Sinal.RECIVE_READ_ALL_OUT_IO.length()?hex.substring(0, IO88Sinal.RECIVE_READ_ALL_OUT_IO.length()):hex;
				}else {
					hex = "";
				}

            } catch (Exception e) {
                hex = "";
            }
            try {

                if(hex.length()!=0&&hex.length()<8) {
                    for(int i=0;i<8-hex.length();i++) {
                        hex = "0"+hex;
                    }
                }
                //System.out.println("-----_____-----"+hex);
                if(StringUtils.isNoneEmpty(hex)) {
                    hex = new StringBuffer(HexUtil.hexString2binaryString(hex)).reverse().substring(bitsit).toString();
                }
			} catch (Exception e) {
				hex = "";
			}
			

			
			return hex;
		}

		public int getBitsit() {
			return bitsit;
		}

		public void setBitsit(int bitsit) {
			this.bitsit = bitsit;
		}
		
	}
	
	
	public static void main(String[] args) {
		String n = "admin\\r\\n";
		n = n.replace("\\r", "\r").replace("\\n", "\n");
		System.out.println(n+"   "+HexUtil.toHex(n));
	}

	@Override
	public void setDeviceCallback(IDeviceStateCallback deviceCallback) {
		// TODO Auto-generated method stub
		
	}
	
}
